package com.example.controller;

import com.example.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/file")
@CrossOrigin(origins = "*")
public class FileController {
    
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    
    @Autowired
    private FileService fileService;
    
    @GetMapping("/list/{serverId}")
    public ResponseEntity<Page<String>> listFiles(
            @PathVariable Long serverId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        try {
            logger.info("Listing files for server {} with page {}, size {}, search: {}", serverId, page, size, search);
            Page<String> files = fileService.listFiles(serverId, PageRequest.of(page, size), search);
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            logger.error("Error listing files", e);
            throw new RuntimeException("Error listing files: " + e.getMessage());
        }
    }
    
    @GetMapping("/exists/{serverId}/{fileName}")
    public ResponseEntity<Boolean> checkFileExists(@PathVariable Long serverId, @PathVariable String fileName) {
        try {
            logger.info("Checking if file {} exists on server {}", fileName, serverId);
            boolean exists = fileService.checkFileExists(serverId, fileName);
            return ResponseEntity.ok(exists);
        } catch (Exception e) {
            logger.error("Error checking file existence", e);
            throw new RuntimeException("Error checking file existence: " + e.getMessage());
        }
    }

    @PostMapping("/upload/{serverId}")
    public ResponseEntity<String> uploadFile(
            @PathVariable Long serverId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "overwrite", defaultValue = "false") boolean overwrite) {
        try {
            // 检查文件是否存在
            if (fileService.checkFileExists(serverId, file.getOriginalFilename())) {
                // 文件存在且不允许覆盖，返回提示信息给前端
                if (!overwrite) {
                    return ResponseEntity.status(409).body("File already exists. Do you want to overwrite?");
                }
            }

            // 如果文件不存在或允许覆盖，继续上传文件
            fileService.uploadFile(serverId, file, overwrite);
            return ResponseEntity.ok("File uploaded successfully");

        } catch (Exception e) {
            // 错误处理
            logger.error("Error uploading file", e);
            throw new RuntimeException("Error uploading file: " + e.getMessage());
        }
    }
    
    @PostMapping("/overwrite/{serverId}")
    public ResponseEntity<String> overwriteFile(
            @PathVariable Long serverId,
            @RequestParam("file") MultipartFile file) {
        try {
            // 强制覆盖文件
            fileService.uploadFile(serverId, file, true);
            return ResponseEntity.ok("File overwritten successfully");
        } catch (Exception e) {
            logger.error("Error overwriting file", e);
            throw new RuntimeException("Error overwriting file: " + e.getMessage());
        }
    }
    
    @GetMapping("/download/{serverId}/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable Long serverId, @PathVariable String fileName) {
        try {
            logger.info("Downloading file {} from server {}", fileName, serverId);
            byte[] fileContent = fileService.downloadFile(serverId, fileName);
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"")
                    .body(fileContent);
        } catch (Exception e) {
            logger.error("Error downloading file", e);
            throw new RuntimeException("Error downloading file: " + e.getMessage());
        }
    }
} 